from math import ceil
import os
import sys
from unittest import expectedFailure
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.append(BASE_DIR)
sys.path.append(r'C:\Users\Administrator\Desktop\arai\Source\Astar20221013')

from pipe_tee import *
from duct_tee import *
from Source.SSF import Astar
from Source.HJL import PipeClass
from Source.HJL import BlockClass
from Source.LYZ import pipeAdjust, getHeight
from dbConnection.db_CURD import progress,message_info,err_info,setStatus,endTime,info
from secondary_main import *

def try_main(paths,id):
    main(paths,id)
    # try:
    #     main(paths,id)
    #     print("main执行完毕，step改为3")
    # except:
    #     print('main函数执行异常,状态设置为 status = 2')
    #     setStatus(id,2)

def main(paths,id):
    user_config = paths[0]
    revit_data = paths[1]
    revit_order = paths[2]

    blockBase = BlockClass.BlockBase(revit_data)
    pipeBase = PipeClass.PipeBase(revit_order)

    pipeBase.sizeOrder()

    pipeBase_copy = copy.deepcopy(pipeBase)#拷贝pipebase，为了三通fitting而设置

    block_arr = qyhf.blocks_to_arr(blockBase)
    block_arr_copy = copy.deepcopy(block_arr)
    block_arr = qyhf.pipes_to_blocks(block_arr, 10)  # 加安装空间
    #print('block_arr_copy',block_arr_copy)
    # 输出的信息
    output_pip_Link = []

    ceilling = [0, 0]
    floor, ceilling[0], ceilling[1], flag = getHeight.get_floor_height(revit_data,user_config)
    # ceilling = [-float('inf'),float('inf')]
    print('ceilling floor', ceilling, floor)
    # if flag:
    #     set_Initial_height(pipeBase, ceilling)

    pipeGroups_arr = pipes_getGroup(pipeBase)
    # print('----', pipeGroups_arr)
    # pipeGroups_arr = setHeight(revit_data,user_config,pipeGroups_arr)

    if(pipeGroups_arr == []):
        print('管道为空')
        errmes = "算法检测到管道为空，请检测输入是否有问题！"
        info(errmes)
        setStatus(id, 2)
        return

    new_allpipelist = []
    Group_index = 1
    err_pipegroups = 0
    err_index = {}
    flag = 0 #算法flag，0为逻辑，1为A*
    for PipeGroup in pipeBase._pipeGroups:
        PipeGroup_info = [PipeGroup.pipeGroupNo, PipeGroup.type, ceilling, floor] #PipeGroup_info信息为管道组号、管道组类型、天花板高度、地板高度
        try:
            # 如果是不含三通水管,则跑原来程序:
            if PipeGroup._teeList == []:
                print("程序正在运行第" + str(Group_index) + "组管道，一共有"+ str(len(pipeGroups_arr)) + "组管道,当前组管道标号pipeGroup = "+str(PipeGroup.pipeGroupNo))
                progress(Group_index - 1,len(pipeGroups_arr))
                message_info("程序正在运行第" + str(Group_index) + "组管道，一共有"+ str(len(pipeGroups_arr)) + "组管道")

                print('*************当前组(pipeGroupNo ='+str(PipeGroup.pipeGroupNo)+')管道不含三通,跑原来算法*************')
                pipegroup_main(pipeBase, blockBase, block_arr, PipeGroup_info, new_allpipelist, flag,output_pip_Link)
            #否则，跑水管三通程序:
            else:
                print("程序正在运行第" + str(Group_index) + "组管道，一共有"+ str(len(pipeGroups_arr)) + "组管道,当前组管道标号pipeGroup = "+str(PipeGroup.pipeGroupNo))
                progress(Group_index - 1,len(pipeGroups_arr))
                message_info("程序正在运行第" + str(Group_index) + "组管道，一共有"+ str(len(pipeGroups_arr)) + "组管道")

                if (PipeGroup.type =='LineDuct') or (PipeGroup.type == 'Duct'):
                    print('*************当前组(pipeGroupNo =' + str(PipeGroup.pipeGroupNo) + ')管道为含三通风管,跑风管三通算法*************')

                    #plist_flag决定每列管道的排管算法
                    plist_flag = []
                    for i in range(0,len(PipeGroup._pipeLists)+1):
                        plist_flag.append(flag)
                    Duct_Tee_Sorting(pipeBase, blockBase, block_arr, PipeGroup_info, new_allpipelist, plist_flag)

                else:
                    print('*************当前组(pipeGroupNo =' + str(PipeGroup.pipeGroupNo) + ')管道含三通水管,跑水管三通算法*************')
                    Tee_sorting(pipeBase, blockBase, block_arr, PipeGroup_info, new_allpipelist, flag)
        except:#8.11为了测试新增加的，将跑不通的管道返回原管道
            print('当前管道组(pipeGroupNo ='+str(PipeGroup.pipeGroupNo)+')排管算法出错,返回原管道!')
            PipeGroup_info = PipeGroupNo_to_PipeGroup(PipeGroup.pipeGroupNo, pipeBase)  # PipeGroup_info中的信息为：管道组数组、管道组类型

            #还原pipebase为输入
            for PipeGroup1 in pipeBase_copy._pipeGroups:
                if PipeGroup1.pipeGroupNo == PipeGroup.pipeGroupNo:
                    pipeBase._pipeGroups = [PipeGroup1 if i ==PipeGroup else i for i in pipeBase._pipeGroups ]
                    break
            
            for pipe in PipeGroup_info[0]:
                new_allpipelist.append(pipe)
                try:
                    new_blocklist = qyhf.pipes_to_blocks(pipe, 10)
                except:
                    break
                # # 管道类型的障碍物，添加到障碍物对象中
                add(new_blocklist, blockBase)
                # # 管道类型的障碍物，添加到障碍物数组中
                block_arr.extend(new_blocklist)
            err_pipegroups +=1
            err_index['Group_index:'+str(Group_index)] = 'pipeGroupNo:'+ str(PipeGroup.pipeGroupNo)
        Group_index = Group_index + 1
    # print(pipeBase._pipeGroups[0]._pipeLists[1]._pipes[0].start)
    tee_fitting(pipeBase,pipeBase_copy) #为三通管道添加连接关系
    print('所有管道', new_allpipelist)
    print('跑不通的管道组数量:',err_pipegroups)
    print('跑不通的管道组:', err_index)
    # LYZ 0824
    # try:
    # pipeAdjust.pipes_adjust_main(pipeBase, block_arr_copy)
    # except:
    #     print('微调出错，返回避障后原管道')
    # LYZ 0824
    # todo 重新跑一遍
    # 输出检查机制表
    out_excel(output_pip_Link,"C:/revit_data_v3/" + str(id))
    # 输出xml
    pipeBase.output_sizeOrder()
    pipeBase.outputXml("C:/revit_data_v3/" + str(id) + "/revit_order_new.xml")
    endTime()

def ID2path(id):
    data_path = "C:/revit_data_v3/" + str(id) + "/revit_data.xml"
    config_path = "C:/revit_data_v3/" + str(id) + "/user_config.xml"
    order_path = "C:/revit_data_v3/" + str(id) + "/revit_order.xml"
    # print(data_path, config_path, order_path)
    return [config_path, data_path, order_path]
if __name__ == '__main__':
    # 检测数据库任务，开启事务
    main(ID2path(540),540)
#   updateStatus()